3 class MWContentSerializationException
extends MWException
{
9 * A content handler knows how do deal with a specific type of content on a wiki page.
10 * Content is stored in the database in a serialized form (using a serialization format aka mime type)
11 * and is be unserialized into it's native PHP represenation (the content model).
13 * Some content types have a flat model, that is, their native represenation is the
14 * same as their serialized form. Examples would be JavaScript and CSS code. As of now,
15 * this also applies to wikitext (mediawiki's default content type), but wikitext
16 * content may be represented by a DOM or AST structure in the future.
19 abstract class ContentHandler
{
21 public static function getContentText( Content
$content = null ) {
22 global $wgContentHandlerTextFallback;
24 if ( !$content ) return '';
26 if ( $content instanceof TextContent
) {
27 return $content->getNativeData();
30 if ( $wgContentHandlerTextFallback == 'fail' ) throw new MWException( "Attempt to get text from Content with model " . $content->getModelName() );
31 if ( $wgContentHandlerTextFallback == 'serialize' ) return $content->serialize();
36 public static function makeContent( $text, Title
$title, $modelName = null, $format = null ) {
38 $modelName = $title->getContentModelName();
41 $handler = ContentHandler
::getForModelName( $modelName );
42 return $handler->unserialize( $text, $format );
45 public static function getDefaultModelFor( Title
$title ) {
46 global $wgNamespaceContentModels;
48 # NOTE: this method must not rely on $title->getContentModelName() directly or indirectly,
49 # because it is used to initialized the mContentModelName memebr.
51 $ns = $title->getNamespace();
57 if ( !empty( $wgNamespaceContentModels[ $ns ] ) ) {
58 $model = $wgNamespaceContentModels[ $ns ];
61 # hook can determin default model
62 if ( !wfRunHooks( 'DefaultModelFor', array( $title, &$model ) ) ) { #FIXME: document new hook!
63 if ( $model ) return $model;
66 # Could this page contain custom CSS or JavaScript, based on the title?
67 $isCssOrJsPage = ( NS_MEDIAWIKI
== $ns && preg_match( '!\.(css|js)$!u', $title->getText(), $m ) );
68 if ( $isCssOrJsPage ) $ext = $m[1];
70 # hook can force js/css
71 wfRunHooks( 'TitleIsCssOrJsPage', array( $title, &$isCssOrJsPage ) );
73 # Is this a .css subpage of a user page?
74 $isJsCssSubpage = ( NS_USER
== $ns && !$isCssOrJsPage && preg_match( "/\\/.*\\.(js|css)$/", $title->getText(), $m ) );
75 if ( $isJsCssSubpage ) $ext = $m[1];
77 # is this wikitext, according to $wgNamespaceContentModels or the DefaultModelFor hook?
78 $isWikitext = ( $model == CONTENT_MODEL_WIKITEXT ||
$model === null );
79 $isWikitext = ( $isWikitext && !$isCssOrJsPage && !$isJsCssSubpage );
81 # hook can override $isWikitext
82 wfRunHooks( 'TitleIsWikitextPage', array( $title, &$isWikitext ) );
87 return CONTENT_MODEL_JAVASCRIPT
;
88 else if ( $ext == 'css' )
89 return CONTENT_MODEL_CSS
;
94 return CONTENT_MODEL_TEXT
;
97 # we established that is must be wikitext
98 return CONTENT_MODEL_WIKITEXT
;
101 public static function getForTitle( Title
$title ) {
102 $modelName = $title->getContentModelName();
103 return ContentHandler
::getForModelName( $modelName );
106 public static function getForContent( Content
$content ) {
107 $modelName = $content->getModelName();
108 return ContentHandler
::getForModelName( $modelName );
113 * @param $modelName String the name of the content model for which to get a handler. Use CONTENT_MODEL_XXX constants.
114 * @return ContentHandler
115 * @throws MWException
117 public static function getForModelName( $modelName ) {
118 global $wgContentHandlers;
120 if ( empty( $wgContentHandlers[$modelName] ) ) {
122 wfRunHooks( "ContentHandlerForModelName", array( $modelName, &$handler ) ); #FIXME: document new hook
124 if ( $handler ) { # NOTE: may be a string or an object, either is fine!
125 $wgContentHandlers[$modelName] = $handler;
127 throw new MWException( "No handler for model $modelName registered in \$wgContentHandlers" );
131 if ( is_string( $wgContentHandlers[$modelName] ) ) {
132 $class = $wgContentHandlers[$modelName];
133 $wgContentHandlers[$modelName] = new $class( $modelName );
136 return $wgContentHandlers[$modelName];
139 # ----------------------------------------------------------------------------------------------------------
140 public function __construct( $modelName, $formats ) {
141 $this->mModelName
= $modelName;
142 $this->mSupportedFormats
= $formats;
145 public function getModelName() {
146 # for wikitext: wikitext; in the future: wikiast, wikidom?
147 # for wikidata: wikidata
148 return $this->mModelName
;
151 protected function checkModelName( $modelName ) {
152 if ( $modelName !== $this->mModelName
) {
153 throw new MWException( "Bad content model: expected " . $this->mModelName
. " but got found " . $modelName );
157 public function getSupportedFormats() {
158 # for wikitext: "text/x-mediawiki-1", "text/x-mediawiki-2", etc
159 # for wikidata: "application/json", "application/x-php", etc
160 return $this->mSupportedFormats
;
163 public function getDefaultFormat() {
164 return $this->mSupportedFormats
[0];
167 public function isSupportedFormat( $format ) {
168 if ( !$format ) return true; # this means "use the default"
170 return in_array( $format, $this->mSupportedFormats
);
173 protected function checkFormat( $format ) {
174 if ( !$this->isSupportedFormat( $format ) ) {
175 throw new MWException( "Format $format is not supported for content model " . $this->getModelName() );
181 * @param Content $content
182 * @param null $format
185 public abstract function serialize( Content
$content, $format = null );
189 * @param $blob String
190 * @param null $format
193 public abstract function unserialize( $blob, $format = null );
195 public abstract function emptyContent();
198 * Return an Article object suitable for viewing the given object
200 * NOTE: does *not* do special handling for Image and Category pages!
201 * Use Article::newFromTitle() for that!
205 * @todo Article is being refactored into an action class, keep track of that
207 public function createArticle( Title
$title ) {
208 $this->checkModelName( $title->getContentModelName() );
210 $article = new Article($title);
215 * Return an EditPage object suitable for editing the given object
217 * @param type $article
220 public function createEditPage( Article
$article ) {
221 $this->checkModelName( $article->getContentModelName() );
223 $editPage = new EditPage( $article );
228 * Return an ExternalEdit object suitable for editing the given object
230 * @param type $article
231 * @return \ExternalEdit
233 public function createExternalEdit( IContextSource
$context ) {
234 $this->checkModelName( $context->getTitle()->getModelName() );
236 $externalEdit = new ExternalEdit( $context );
237 return $externalEdit;
242 * @param $context IContextSource context to use, anything else will be ignored
243 * @param $old Integer old ID we want to show and diff with.
244 * @param $new String either 'prev' or 'next'.
245 * @param $rcid Integer ??? FIXME (default 0)
246 * @param $refreshCache boolean If set, refreshes the diff cache
247 * @param $unhide boolean If set, allow viewing deleted revs
249 public function getDifferenceEngine( IContextSource
$context, $old = 0, $new = 0, $rcid = 0, #FIMXE: use everywhere!
250 $refreshCache = false, $unhide = false ) {
252 $this->checkModelName( $context->getTitle()->getModelName() );
254 $de = new DifferenceEngine( $context, $old, $new, $rcid, $refreshCache, $unhide );
260 * attempts to merge differences between three versions.
261 * Returns a new Content object for a clean merge and false for failure or a conflict.
263 * This default implementation always returns false.
265 * @param $oldContent String
266 * @param $myContent String
267 * @param $yourContent String
268 * @return Content|Bool
270 public function merge3( Content
$oldContent, Content
$myContent, Content
$yourContent ) {
275 * Return an applicable autosummary if one exists for the given edit.
277 * @param $oldContent Content: the previous text of the page.
278 * @param $newContent Content: The submitted text of the page.
279 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
281 * @return string An appropriate autosummary, or an empty string.
283 public function getAutosummary( Content
$oldContent, Content
$newContent, $flags ) {
286 # Decide what kind of autosummary is needed.
288 # Redirect autosummaries
289 $ot = $oldContent->getRedirectTarget();
290 $rt = $newContent->getRedirectTarget();
292 if ( is_object( $rt ) && ( !is_object( $ot ) ||
!$rt->equals( $ot ) ||
$ot->getFragment() != $rt->getFragment() ) ) {
294 $truncatedtext = $newContent->getTextForSummary(
296 - strlen( wfMsgForContent( 'autoredircomment' ) )
297 - strlen( $rt->getFullText() ) );
299 return wfMsgForContent( 'autoredircomment', $rt->getFullText(), $truncatedtext );
302 # New page autosummaries
303 if ( $flags & EDIT_NEW
&& $newContent->getSize() > 0 ) {
304 # If they're making a new article, give its text, truncated, in the summary.
306 $truncatedtext = $newContent->getTextForSummary(
307 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) );
309 return wfMsgForContent( 'autosumm-new', $truncatedtext );
312 # Blanking autosummaries
313 if ( $oldContent->getSize() > 0 && $newContent->getSize() == 0 ) {
314 return wfMsgForContent( 'autosumm-blank' );
315 } elseif ( $oldContent->getSize() > 10 * $newContent->getSize() && $newContent->getSize() < 500 ) {
316 # Removing more than 90% of the article
318 $truncatedtext = $newContent->getTextForSummary(
319 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) );
321 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
324 # If we reach this point, there's no applicable autosummary for our case, so our
325 # autosummary is empty.
330 * Auto-generates a deletion reason
332 * @param $title Title: the page's title
333 * @param &$hasHistory Boolean: whether the page has a history
334 * @return mixed String containing deletion reason or empty string, or boolean false
335 * if no revision occurred
337 public function getAutoDeleteReason( Title
$title, &$hasHistory ) {
340 $dbw = wfGetDB( DB_MASTER
);
342 // Get the last revision
343 $rev = Revision
::newFromTitle( $title );
345 if ( is_null( $rev ) ) {
349 // Get the article's contents
350 $content = $rev->getContent();
353 // If the page is blank, use the text from the previous revision,
354 // which can only be blank if there's a move/import/protect dummy revision involved
355 if ( $content->getSize() == 0 ) {
356 $prev = $rev->getPrevious();
359 $content = $rev->getContent();
364 // Find out if there was only one contributor
365 // Only scan the last 20 revisions
366 $res = $dbw->select( 'revision', 'rev_user_text',
367 array( 'rev_page' => $title->getArticleID(), $dbw->bitAnd( 'rev_deleted', Revision
::DELETED_USER
) . ' = 0' ),
369 array( 'LIMIT' => 20 )
372 if ( $res === false ) {
373 // This page has no revisions, which is very weird
377 $hasHistory = ( $res->numRows() > 1 );
378 $row = $dbw->fetchObject( $res );
380 if ( $row ) { // $row is false if the only contributor is hidden
381 $onlyAuthor = $row->rev_user_text
;
382 // Try to find a second contributor
383 foreach ( $res as $row ) {
384 if ( $row->rev_user_text
!= $onlyAuthor ) { // Bug 22999
393 // Generate the summary with a '$1' placeholder
395 // The current revision is blank and the one before is also
396 // blank. It's just not our lucky day
397 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
400 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
402 $reason = wfMsgForContent( 'excontent', '$1' );
406 if ( $reason == '-' ) {
407 // Allow these UI messages to be blanked out cleanly
411 // Max content length = max comment length - length of the comment (excl. $1)
412 $text = $content->getTextForSummary( 255 - ( strlen( $reason ) - 2 ) );
414 // Now replace the '$1' placeholder
415 $reason = str_replace( '$1', $text, $reason );
421 * Get the Content object that needs to be saved in order to undo all revisions
422 * between $undo and $undoafter. Revisions must belong to the same page,
423 * must exist and must not be deleted
424 * @param $undo Revision
425 * @param $undoafter null|Revision Must be an earlier revision than $undo
426 * @return mixed string on success, false on failure
428 public function getUndoContent( Revision
$current, Revision
$undo, Revision
$undoafter = null ) {
429 $cur_content = $current->getContent();
431 if ( empty( $cur_content ) ) {
432 return false; // no page
435 $undo_content = $undo->getContent();
436 $undoafter_content = $undoafter->getContent();
438 if ( $cur_content->equals( $undo_content ) ) {
439 # No use doing a merge if it's just a straight revert.
440 return $undoafter_content;
443 $undone_content = $this->merge3( $undo_content, $undoafter_content, $cur_content );
445 return $undone_content;
450 abstract class TextContentHandler
extends ContentHandler
{
452 public function __construct( $modelName, $formats ) {
453 parent
::__construct( $modelName, $formats );
456 public function serialize( Content
$content, $format = null ) {
457 $this->checkFormat( $format );
458 return $content->getNativeData();
462 * attempts to merge differences between three versions.
463 * Returns a new Content object for a clean merge and false for failure or a conflict.
465 * This text-based implementation uses wfMerge().
467 * @param $oldContent String
468 * @param $myContent String
469 * @param $yourContent String
470 * @return Content|Bool
472 public function merge3( Content
$oldContent, Content
$myContent, Content
$yourContent ) {
473 $this->checkModelName( $oldContent->getModelName() );
474 #TODO: check that all Content objects have the same content model! #XXX: what to do if they don't?
476 $format = $this->getDefaultFormat();
478 $old = $this->serialize( $oldContent, $format );
479 $mine = $this->serialize( $myContent, $format );
480 $yours = $this->serialize( $yourContent, $format );
482 $ok = wfMerge( $old, $mine, $yours, $result );
484 if ( !$ok ) return false;
485 if ( !$result ) return $this->emptyContent();
487 $mergedContent = $this->unserialize( $result, $format );
488 return $mergedContent;
493 class WikitextContentHandler
extends TextContentHandler
{
495 public function __construct( $modelName = CONTENT_MODEL_WIKITEXT
) {
496 parent
::__construct( $modelName, array( 'application/x-wikitext' ) ); #FIXME: mime
499 public function unserialize( $text, $format = null ) {
500 $this->checkFormat( $format );
502 return new WikitextContent( $text );
505 public function emptyContent() {
506 return new WikitextContent( "" );
512 #TODO: make ScriptContentHandler base class with plugin interface for syntax highlighting!
514 class JavaScriptContentHandler
extends TextContentHandler
{
516 public function __construct( $modelName = CONTENT_MODEL_WIKITEXT
) {
517 parent
::__construct( $modelName, array( 'text/javascript' ) ); #XXX: or use $wgJsMimeType? this is for internal storage, not HTTP...
520 public function unserialize( $text, $format = null ) {
521 return new JavaScriptContent( $text );
524 public function emptyContent() {
525 return new JavaScriptContent( "" );
529 class CssContentHandler
extends TextContentHandler
{
531 public function __construct( $modelName = CONTENT_MODEL_WIKITEXT
) {
532 parent
::__construct( $modelName, array( 'text/css' ) );
535 public function unserialize( $text, $format = null ) {
536 return new CssContent( $text );
539 public function emptyContent() {
540 return new CssContent( "" );